package com.msb.strategy.filter.impl;

import com.msb.common.constart.CacheConstant;
import com.msb.common.enums.ExceptionEnums;
import com.msb.common.exception.ApiException;
import com.msb.common.model.StandardSubmit;
import com.msb.strategy.feign.BeaconCacheClient;
import com.msb.strategy.filter.StrategyFilter;
import com.msb.strategy.util.ClientBalanceUtil;
import com.msb.strategy.util.ErrorSendMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: lmf
 * @Create: 2025/3/13 21:01
 * @module
 */
@Slf4j
@Service(value = "fee")
public class FeeStrategyFilter implements StrategyFilter {
    @Autowired
    private BeaconCacheClient cacheClient;

    @Resource
    private ErrorSendMessage errorSendMessage;

    @Override
    public void strategy(StandardSubmit submit) {
        log.info("费用扣除策略开始---");
        String BALANCE = "balance";
        // 获取扣费金额
        Long fee = submit.getFee();
        // 从redis中扣除费用并返回当前客户的余额
        final Long surplusMoney = cacheClient.hIncrement(CacheConstant.CLIENT_BALANCE + submit.getClientId(), BALANCE, -fee);
        // 判断余额是否充足
        if (surplusMoney < ClientBalanceUtil.getClientBalance(submit.getClientId())) {
            // 超出欠费最大金额提示异常并把扣除的费用还回去 不发送短信
            log.error("费用扣除---余额不足");

            // 返回费用
            cacheClient.hIncrement(CacheConstant.CLIENT_BALANCE + submit.getClientId(), BALANCE, fee);

            // 记录异常
            submit.setErrorMessage(ExceptionEnums.BALANCE_NOT_ENOUGH.getMsg());
            errorSendMessage.sendErrorMessage(submit, ExceptionEnums.BALANCE_NOT_ENOUGH);
        }
        ;
        log.info("费用扣除---成功");
    }
}
